package day10;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class Demo07 {
    public static void main(String[] args) {
        /**
         * count.txt(一个特别大的文件)
         * B7151890053952,B7151890053952,B7151890053952,
         * B7151890053952,B7151890053952,39101880590647,
         * 39101880590647,39101880612299,39101880590647,
         * 39101880590647,39101880590647,39101880612299,
         * 39101880612299,39101880590647,39101880590647,
         * 39101880590647...
         *
         * 1. 将count文件用程序读取，并打印在控制台上
         * 2. 将count内逗号分割的段落数统计出来
         *    - 一共有多少个段落？
         *    - 每个段落出现的次数？
         *    - 对结果进行排序
         * 3. 将结果通过txt或excel输出到文件
         *    csv文件, 由逗号分割的文本文件
         */
        String filename = "count源文件.txt";
        try(InputStreamReader in = new InputStreamReader(
            new BufferedInputStream(
            new FileInputStream(filename)), StandardCharsets.UTF_8
        )){
            StringBuilder buf = new StringBuilder();
            int c;
            int count = 0;
            Map<String, Integer> countMap = new HashMap<>();
            while ((c = in.read())!=-1){
                if (c == ','){
                    String key = buf.toString();
                    System.out.println(key+",");
                    buf.delete(0, buf.length());
                    Integer n = countMap.get(key);
                    countMap.put(key, n==null ? 1 : n+1);
                    count++;
                }else {
                    buf.append((char) c);
                }
            }
            List<Map.Entry<String, Integer>> list = new ArrayList<>(countMap.entrySet());
            list.sort(Comparator.comparingInt(Map.Entry::getValue));
            //list.forEach(System.out::println);
            //System.out.println("总数:"+count);
            PrintWriter out = new PrintWriter("result.csv","GBK");
            out.println("段落,数量");
            list.forEach(entry -> {
                out.print("=\"");
                out.print(entry.getKey());
                out.print("\"");
                out.print(",");
                out.println(entry.getValue());
            });
            out.print("总数,");
            out.println(count);
            out.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
